package com.car.slave.im.receiver;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;

/**
 * 登陆广播.
 * @author zhangliucheng
 *
 */
public class IMLoginReceiver extends BroadcastReceiver {

	public enum InitExceptionStatus {
		NETWORK,
		Invalid
	}

	public interface OnLoginCallback {
		void onSuccess();
		void onFailed(InitExceptionStatus exceptionStatus);
	}
	
	private final OnLoginCallback onInitCallback;
	
	public IMLoginReceiver(OnLoginCallback onInitCallback) {
		super();
		this.onInitCallback = onInitCallback;
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		String data = intent.getStringExtra("data");
		try {
			JSONObject obj = new JSONObject(data);
			boolean success = obj.optInt("err_code") == 0;
			if (success) {
				// 移除广播
				LocalBroadcastManager.getInstance(context).unregisterReceiver(this);

				onInitCallback.onSuccess();
			} else {
				onInitCallback.onFailed(InitExceptionStatus.NETWORK);
			}
		} catch (JSONException e) {
			// 服务器返回来的错误信息
			onInitCallback.onFailed(InitExceptionStatus.Invalid);
		}
	}
	
	/**
	 * 注册广播.
	 * @param context
	 * @param onInitCallback
	 */
	public static void onRegisterReceiver(Context context, OnLoginCallback onInitCallback) {
		IMLoginReceiver receiver = new IMLoginReceiver(onInitCallback);
		LocalBroadcastManager.getInstance(context).registerReceiver(receiver, receiver.getIntentFilter());
	}
	
	/**
	 * 发送failed广播.
	 * @param context
	 */
	public static void postLoginBroadcast(Context context, String data) {
		Intent intent = new Intent(getLoginAction());
		intent.putExtra("data", data);
		LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
	}
	
	private static String getLoginAction() {
		return "com.imchezhil.im.receiver.initSuccess";
	}
	
	private IntentFilter getIntentFilter() {
		IntentFilter filter = new IntentFilter();
		filter.addAction(getLoginAction());
		return filter;
	}
}
